import { _decorator, Component, Node, Collider2D, Contact2DType, IPhysics2DContact, director, Director, sp } from 'cc';
import { Block } from '../Block/Block';
import { SoundManager, SoundType } from '../SoundManager';
import Common from '../Config/Common';
const { ccclass, property } = _decorator;
/** 爆炸弹爆炸 */
@ccclass('ExplodeBomb')
export class ExplodeBomb extends Component {

    @property(sp.Skeleton) // 绑定 Spine 组件
    explodeSpine: sp.Skeleton = null;

    /** 爆炸伤害 */
    damage: number = 1;

    onLoad(): void {
        if (this.explodeSpine) {
            SoundManager.instance.playSound(SoundType.Bomb);
            let aniName = 'BaoZha';
            Common.instance.playSpine(this.explodeSpine, aniName, false, null, () => {
                director.once(Director.EVENT_AFTER_PHYSICS, () => {
                    this.node.parent.destroy();
                })
            });
        }
    }

    onEnable() {
        // 监听碰撞事件
        let collider = this.getComponent(Collider2D);
        if (collider) {
            collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
            collider.on(Contact2DType.END_CONTACT, this.onEndContact, this);
        }
    }
    onDisable() {
        // 取消监听碰撞事件
        const collider = this.getComponent(Collider2D);
        if (collider) {
            collider.off(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
            collider.off(Contact2DType.END_CONTACT, this.onEndContact, this);
        }
    }

    onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
        // 只在两个碰撞体开始接触时被调用一次
        const selfNode = selfCollider.node;
        const otherNode = otherCollider.node;
        if (selfNode.name === 'BombExplodeNode' && otherNode.name === 'Block') {
            this.onHandleCollider(otherNode, selfNode)
        } else if (selfNode.name === "Block" && otherNode.name === 'BombExplodeNode') {
            this.onHandleCollider(selfNode, otherNode)
        }
    }
    onEndContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {}

    /** 处理子弹碰撞 */
    onHandleCollider(blockNode: Node, bulletNode: Node) {
        if (blockNode && blockNode.getComponent(Block)) {
            blockNode.getComponent(Block).onDamage(this.damage);
        }
    }
}
